package com.lee.boot.head.first.demo.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lee.boot.head.first.demo.entity.Role;


import com.lee.boot.head.first.demo.entity.User;
import com.lee.boot.head.first.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author edz
 */
@Service
@Primary
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    UserService userService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        List<Role> roles = userService.listByUsername(username);
        User one = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getUserName, username));
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>(10);
        for (Role role : roles) {
            GrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(role.getRoleName());
            grantedAuthorities.add(simpleGrantedAuthority);
        }
        UserDetails user =
                new org.springframework.security.core.userdetails.User(one.getUserName(), one.getPwd(), grantedAuthorities);
        return user;
    }
}
